import { Injectable, NgZone } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
import { OrderService } from './order.service';

@Injectable({
    providedIn: 'root',
})
export class SignalrService {
    private hub: HubConnection | undefined;

    constructor(private orderService: OrderService, private ngZone: NgZone) {}

    connect() {
        this.hub = new HubConnectionBuilder()
            .withUrl('http://localhost:5000/notifications')
            .build();

        this.hub.on('orderStatusChanged', (orderId, newStatus) => {
            this.ngZone.runOutsideAngular(() => {
                this.orderService.updateOrderStatus(orderId, newStatus);
            });
        });

        this.hub.start();
    }
}